#!/bin/bash docker-compose方式启动脚本，放置在远程服务docker目录下，即：DOCKER_DIR

# 设置目标目录
DOCKER_DIR="/home/agilerobots/docker/"

# 日志输出函数
log() {
  echo "$(date +'%Y-%m-%d %H:%M:%S') - $1"
}

# 确保.env文件存在
if [ ! -f "${DOCKER_DIR}.env" ]; then
  log "Error: .env file not found at ${DOCKER_DIR}.env"
  exit 1
fi

# 输出.env文件内容
log ".env file content:"
cat "${DOCKER_DIR}.env"

# 停止并移除现有容器
log "Stopping and removing containers..."
if ! docker-compose -f "${DOCKER_DIR}docker-compose.yml" down; then
  log "Failed to stop and remove containers."
  exit 1
fi

# 删除相关镜像
log "Removing images..."
remove_images() {
  local image_prefix=$1
  docker images --filter=reference="${image_prefix}:*" --format '{{.ID}}' | xargs -r docker rmi -f
}

remove_images 'mr-fleet-boot'
remove_images 'mr-fleet-gateway'

# 构建并启动服务
log "Building and starting services..."
if ! docker-compose --env-file "${DOCKER_DIR}.env" -f "${DOCKER_DIR}docker-compose.yml" up --build -d; then
  log "Failed to build and start services."
  exit 1
fi

log "Services have been successfully updated and started."